package ogdkp.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import ogdkp.om.Bank;
import ogdkp.om.Player;

public class DKPUtils {

	final static String OG_DKP_URL = "http://lesgrognards.net/dkp/listmembers.php";

	public static List<Player> buildPlayerList() {
		final List<Player> players = new ArrayList<Player>();
		fetchFromWebsite(players);
		players.add(new Bank());
		return players;
	}

	/**
	 * Quick and dirty fetch, assumes a certain format
	 */
	private static void fetchFromWebsite(final List<Player> players) {
		try {
			final URL url = new URL(OG_DKP_URL);
			final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				if (line.indexOf("<tr class") >= 0) {
					line = reader.readLine(); // IGNORE checkbox
					line = reader.readLine(); // IGNORE row number
					line = reader.readLine(); // name
					final String name = cleanString(line);

					line = reader.readLine(); // rank
					final String rank = cleanString(line);

					line = reader.readLine(); // level
					final int level = Integer.parseInt(cleanString(line));
					line = reader.readLine(); // class
					final String playerClass = cleanString(line);
					line = reader.readLine(); // IGNORE earned
					line = reader.readLine(); // IGNORE spent
					line = reader.readLine(); // IGNORE adjustment
					line = reader.readLine(); // current
					final int dkp = (int) Float.parseFloat(cleanString(line));
					players.add(new Player(name, rank, playerClass, level, dkp));

				}
			}
			reader.close();
		} catch (final MalformedURLException e) {
			e.printStackTrace();
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Removes HTML tags
	 */
	private static String cleanString(final String input) {
		return input.replaceAll("\\<.*?\\>", "").trim();
	}

}
